<template>
  <div class="my-tabs">
    <div class="my-tabs__header">
      <div class="my-tabs__list-wrap">
        <div class="my-tabs__list">
          <div
            class="my-tabs__item"
            :class="[
                value==item.value?'active':''
            ]"
            v-for="(item,index) in panes"
            :key="index"
            :ref="`tab-${item.value}`"
            @click="handleChange(item)"
          >{{item.label}}</div>
        </div>
        <div class="my-tabs__line" :style="lineStyle"></div>
      </div>
    </div>
    <div class="my-tabs__content">
      <slot />
    </div>
  </div>
</template>
<script>
export default {
  name: "MyTabs",
  props: {
    value: String | Number,
  },
  data() {
    return {
      panes: [],
      lineStyle: null,
    };
  },
  mounted() {
    this.calcPanesInstance();
    this.calcLineStyle();
  },
  methods: {
    calcPanesInstance() {
      const paneSlots = this.$slots.default.filter(
        (vnode) =>
          vnode.tag &&
          vnode.componentOptions &&
          vnode.componentOptions.Ctor.options.name === "MyTabPane"
      );
      const panes = paneSlots.map(({ componentInstance }) => componentInstance);
      this.panes = panes;
      this.tabsList = panes.map((p) => p.label);
    },
    calcLineStyle() {
      this.$nextTick(() => {
        let $tab = this.$refs[`tab-${this.value}`][0];
        const tabStyles = window.getComputedStyle($tab);
        this.lineStyle = {
          width: tabStyles.width,
          transform: `translateX(${
            $tab.offsetLeft + parseFloat(tabStyles.paddingLeft)
          }px)`,
        };
      });
    },
    handleChange(vc) {
      this.$emit("input", vc.value);
      this.calcLineStyle();
    },
  },
};
</script>

<style lang="scss">
.my-tabs {
  box-sizing: border-box;
}

.my-tabs__header {
  margin-bottom: 20px;
  overflow: hidden;
  position: relative;
}

.my-tabs__list-wrap {
  border-bottom: 2px solid #eff2f5;
  position: relative;
}

.my-tabs__line {
  position: absolute;
  bottom: -2px;
  left: 0;
  height: 2px;
  background-color: #00b2ff;
  z-index: 1;
  transition: transform 0.3s;
  transform: translate();
}

.my-tabs__list {
  display: flex;
  flex-wrap: nowrap;

  & > .my-tabs__item {
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    font-size: 14px;
    color: #181c32;
    transition: transform 0.3s;

    &:first-child {
      padding-left: 0;
    }

    &:hover,
    &.active {
      color: #00b2ff;
    }
  }
}

.my-tabs__content {
  overflow: hidden;
  position: relative;
}
</style>